<template>
  <view v-if="shenheStatus == 0" class="page">
    <view class="page-content">
      <view class="content-header">
        <view class="shopInfo">
          <view>{{ $t('facePay.merchant') }}</view>
          <view>{{ store_info.name }}</view>
        </view>
        <image :src="store_info.img" />
      </view>
      <view class="content-body">
        <view class="title">{{ $t('facePay.setMoney') }}</view>
        <view class="input-section">
          <view>￥</view>
          <input v-model="money" :disabled="optionData.price" type="digit" />
        </view>
        <view class="hold-height"></view>
        <view class="title">{{ coupon_list.length ? '优惠' : '' }}</view>
        <view class="remark" v-if="coupon_list.length" @click="showCoupon">
          <text
            >{{ $t('writeOff.discount') }}{{ picker_coupon.sub_price }}</text
          >
          <image :src="asyncImgs.images.face_arrow_right" mode=""></image>
        </view>
      </view>
      <view class="content-foot" :style="[btnStyle]" @click="handleConfirm()">{{
        $t('facePay.pay')
      }}</view>
    </view>
    <!-- 优惠券弹框 -->
    <couponPopup
      ref="coupon_popup"
      @selectCouponCb="selectCouponCb"
      :couponList="coupon_list"
      :coupon="picker_coupon"
    ></couponPopup>
    <login-modal></login-modal>

    <!-- 支付选择弹框 -->
    <!-- 支付类型 -->
    <payWayPopup
      ref="pay_type_list"
      :pay_type_list="pay_type_list"
      @payTypeSelect="payTypeSelect"
    ></payWayPopup>
  </view>
  <Shenhe v-else-if="shenheStatus == 1"></Shenhe>
</template>

<script>
import Shenhe from '@/components/shenhe/shenhe';
import couponPopup from '../components/coupon/popup.vue';
import payWayPopup from '../components/pay-way-popup.vue';
import utils from '../../common/utils';
// import wxPayIcon from "@/static/images/wx_pay_icon.png";
// import accountPayIcon from "@/static/images/account_pay_icon.png";
// import alipaIxcon from "@/static/images/alipay_icon.png";

export default {
  components: {
    Shenhe,
    couponPopup,
    payWayPopup,
  },
  data() {
    return {
      money: '',
      timer: null,
      store_info: {},
      optionData: {},
      goods_id: 0,
      payType_list: [],
      coupon_list: [],
      // #ifdef MP-WEIXIN
      payment: 1, // 当面付，默认为微信支付
      // #endif
      // #ifdef MP-ALIPAY
      payment: 4, // 当面付，默认为微信支付
      // #endif
      picker_coupon: {},
      order_id: '',
      payType: '',
    };
  },
  computed: {
    btnStyle() {
      if (this.money) {
        return { color: '#FFFFFF', background: '#0EB5F8' };
      } else {
        return { color: '#999999', background: '#E0E0E0' };
      }
    },
    pay_type_list() {
      let obj = {
        name: '',
        payment: 0,
        icon: '',
      };
      let arr = [];
      // #ifdef MP-WEIXIN
      obj.name = this.$t('common.payMethod1');
      obj.payment = 1;
      obj.icon = this.asyncImgs.images.wx_pay_icon;
      if (this.stores.payment.adapay_wx?.value) {
        arr.push({
          name: 'Adapay支付',
          payment: 101,
          icon: this.asyncImgs.images.wx_pay_icon,
        });
      }
      // #endif

      // #ifdef MP-ALIPAY
      obj.name = this.$t('common.payMethod4');
      obj.payment = 4;
      obj.icon = this.asyncImgs.images.alipay_icon;
      // #endif

      arr.push(obj);

      return arr;
    },
  },
  watch: {
    money(val) {
      this.getCouponList();
    },
  },
  onLoad(t) {
    // t: price  store_id  user_id
    this.optionData = t;
    if (this.optionData?.price) {
      this.money = this.optionData.price;
    }
    const token = uni.getStorageSync('token');
    if (token) {
      this.getStoreInfo(t);
    }
  },
  methods: {
    // 支付类型选择回调
    payTypeSelect(e) {
      this.payment = e.type;
      this.orderPreview();
    },
    // 获取店铺信息
    getStoreInfo(options) {
      this.$allrequest.facePay.getStoreInfo().then(res => {
        if (!res.code && res.data) {
          this.store_info = res.data.store_info;
          this.getCouponList();
        }
      });
    },
    // 点击付款按钮
    handleConfirm: utils.debounce(that => {
      if (!that.money) return;
      that.$refs.pay_type_list.setShowPayPopup();
      return;
    }, 500),
    // 优惠券列表
    getCouponList() {
      this.$allrequest.facePay
        .getCouponList({
          store_id: this.store_info.id,
          price: this.money || 0,
        })
        .then(res => {
          if (!res.code && res.data) {
            this.goods_id = res.data.goods_id;
            this.payType_list = res.data.payType_list;
            this.coupon_list = res.data.coupon_list;
            // 按满减金额排序
            this.coupon_list.sort((a, b) => {
              return b.sub_price - a.sub_price;
            });
            this.picker_coupon = this.coupon_list[0];
          }
        });
    },
    // 生成订单
    orderPreview() {
      uni.showLoading({
        title: this.$t('order.pay'),
      });
      let mch_list = [
        {
          mch_id: 0,
          goods_list: [
            {
              goods_id: this.goods_id,
              num: 1,
              attr: [{ attr_group_id: 1, attr_id: 1 }],
            },
          ],
        },
      ];
      let params = {
        mch_list: JSON.stringify(mch_list),
        _from: 'mini',
      };
      this.$allrequest.facePay.orderPreview(params).then(res => {
        uni.hideLoading({});
        if (!res.code && res.data) {
          let mch_list_copy = res.data.mch_list;
          mch_list_copy[0]['total_price'] = this.money;
          mch_list_copy[0]['price'] = this.money;
          mch_list_copy[0]['content'] = '';
          mch_list_copy[0]['picker_coupon'] = this.picker_coupon;
          mch_list_copy[0]['coupon_list'] = this.coupon_list;
          let submitParams = {
            payment: this.payment,
            mch_list: JSON.stringify(mch_list_copy),
          };
          this.submitOrder(submitParams);
        }
      });
    },
    // 提交订单
    submitOrder(params) {
      uni.showLoading({
        title: this.$t('facePay.submit'),
      });
      this.$allrequest.facePay.submitOrder(params).then(res => {
        uni.hideLoading();
        if (!res.code && res.data) {
          let payData = {
            order_id: res.data.order_id,
            // store_id: this.optionData.store_id,
            pay_type: this.payment,
            _from: 'mini',
          };
          this.order_id = res.data.order_id;
          // this.payOrder(payData);

          // 拼装跳转支付中间页的数据
          let sub_price = this.picker_coupon?.sub_price
            ? this.picker_coupon?.sub_price
            : 0;
          let payPrice = this.money - sub_price;
          let urlParams = `order_id=${
            res.data.order_id
          }&payPrice=${payPrice}&sub_price=${sub_price}&store_info=${JSON.stringify(
            this.store_info
          )}`;

          let url = `/face-pay/face-pay/result?${urlParams}`;
          let params = {
            payData: {
              order_id: res.data.order_id,
              order_id_list: res.data.order_id_list || '',
              pay_type: this.payment, // todo
            },
            createDate: res.data.add_time, //订单创建时间
            backUrl: url,
            pay_type_list: this.pay_type_list, // todo
            pay_price: payPrice,
            isFacePay: true,
          };
          uni.setStorageSync('payParams', JSON.stringify(params));
          this.$utils.toUrl(`/other/pay/pay?data=getStorage`, 'redirectTo');
          return;
          //
        } else {
          this.errorNotice(res);
        }
      });
    },
    // 提交支付
    payOrder(params) {
      uni.showLoading({
        title: this.$t('order.pay'),
      });
      this.$allrequest.facePay.payOrder(params).then(res => {
        uni.hideLoading();
        if (!res.code && res.data) {
          this.paySubmit(res, params.pay_type);
        } else {
          this.errorNotice(res);
        }
      });
    },

    // 支付操作
    paySubmit(payData, pay_type = 0) {
      if (pay_type == 3 || pay_type == 2) {
        uni.showToast({
          title: payData.msg,
          icon: 'none',
          duration: 2000,
        });
        if (payData.code > 0) {
          return false;
        } else {
          this.show = false;
          return true;
        }
      }
      if (!payData.data) {
        uni.showToast({
          title: payData.msg,
          icon: 'none',
          duration: 2000,
        });
        return false;
      } else {
        const that = this;
        uni.getProvider({
          service: 'payment',
          success: res => {
            // 微信
            if (res.provider.indexOf('wxpay') > -1 && pay_type == 1) {
              // #ifdef MP-WEIXIN
              uni.requestPayment({
                provider: 'wxpay',
                orderInfo: payData.res,
                timeStamp: payData.data.timeStamp,
                nonceStr: payData.data.nonceStr,
                package: payData.data.package,
                signType: payData.data.signType,
                paySign: payData.data.paySign,
                success: res => {},
                complete: res => {
                  if (
                    'requestPayment:fail' != res.errMsg &&
                    'requestPayment:fail cancel' != res.errMsg
                  ) {
                    // 支付成功回调
                    this.paySuccessCb();
                  } else {
                    uni.showToast({
                      title: this.$t('order.payFail'),
                      icon: 'none',
                      duration: 2000,
                    });
                  }
                },
              });
              // #endif

              // #ifdef APP-PLUS
              uni.requestPayment({
                provider: 'wxpay',
                orderInfo: {
                  appid: payData.data.appid, // 微信开放平台 - 应用 - AppId，注意和微信小程序、公众号 AppId 可能不一致
                  noncestr: payData.data.noncestr, // 随机字符串
                  package: payData.data.package, // 固定值
                  partnerid: payData.data.partnerid, // 微信支付商户号
                  prepayid: payData.data.prepayid, // 统一下单订单号
                  timestamp: payData.data.timestamp, // 时间戳（单位：秒）
                  sign: payData.data.sign, // 签名，这里用的 MD5 签名
                },
                complete: res => {
                  if (res.errMsg.indexOf('requestPayment:fail') == -1) {
                    // 支付成功回调
                    this.paySuccessCb();
                  } else {
                    uni.showToast({
                      title: this.$t('order.payFail'),
                      icon: 'none',
                      duration: 2000,
                    });
                  }
                },
              });
              // #endif
            }

            // 支付宝
            if (res.provider.indexOf('alipay') > -1 && pay_type == 4) {
              uni.requestPayment({
                provider: 'alipay',
                orderInfo: payData.data,
                complete: res => {
                  if (res.errMsg.indexOf('requestPayment:fail') == -1) {
                    // 支付成功回调
                    this.paySuccessCb();
                  } else {
                    uni.showToast({
                      title: this.$t('order.notPay'),
                      icon: 'none',
                      duration: 2000,
                    });
                  }
                },
              });
            }
          },
        });
      }
    },

    // 支付成功回调
    paySuccessCb() {
      uni.showToast({
        title: this.$t('order.paySuc'),
        icon: 'none',
        duration: 2000,
      });

      let sub_price = this.picker_coupon?.sub_price
        ? this.picker_coupon?.sub_price
        : 0;
      let payPrice = this.money - sub_price;
      let params = `order_id=${
        this.order_id
      }&payPrice=${payPrice}&sub_price=${sub_price}&store_info=${JSON.stringify(
        this.store_info
      )}`;
      setTimeout(() => {
        this.$utils.toUrl(`/face-pay/face-pay/result?${params}`, 'redirectTo');
      }, 1500);
    },

    // 错误提示
    errorNotice(res) {
      uni.showToast({
        title: res.msg,
        icon: 'none',
        duration: 2000,
      });
    },
    // 点击显示优惠券弹框
    showCoupon() {
      this.$refs.coupon_popup.setShowPopup();
    },
    // 选择优惠券回调事件
    selectCouponCb(e) {
      this.picker_coupon = e.coupon;
    },
  },
};
</script>

<style lang="scss" scoped>
.page {
  width: 100%;
  min-height: 100vh;
  background-color: #f2f2f2;
  font-family: PingFang SC;

  .page-content {
    width: 702rpx;
    margin: 0 auto;

    .content-header {
      width: 100%;
      height: 160rpx;
      background: #f7f7f7;
      border-radius: 14rpx 14rpx 0 0;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 42rpx 50rpx;

      .shopInfo {
        font-size: 34rpx;
        font-weight: 500;
        color: #191919;

        view:last-child {
          font-size: 26rpx;
          font-weight: 400;
          color: #999999;
          margin-top: 18rpx;
        }
      }

      image {
        width: 96rpx;
        height: 96rpx;
        background: #ffffff;
        border-radius: 14rpx;
      }
    }

    .content-body {
      width: 100%;
      background: #ffffff;
      border-radius: 0 0 14rpx 14rpx;
      padding: 58rpx 50rpx 0 50rpx;

      .title {
        font-size: 28rpx;
        font-weight: 400;
        color: #191919;
      }
      .addMargin {
        margin-top: 47rpx;
      }
      .addPadding {
        padding-top: 47rpx;
      }
      .noPadding {
        padding-top: 0;
      }

      .hold-height {
        height: 47rpx;
        width: 100%;
      }

      .input-section {
        display: flex;
        font-size: 78rpx;
        font-weight: 500;
        color: #191919;
        border-bottom: 1rpx solid #e5e5e5;
        view {
          width: 70rpx;
          text-align: left;
        }

        input {
          flex: 1;
          font-size: 112rpx;
          font-weight: 500;
          color: #191919;
          height: 120rpx;
        }
      }

      .remark {
        margin-top: 39rpx;
        padding-bottom: 48rpx;
        font-size: 28rpx;
        font-weight: 400;
        color: #999999;
        display: flex;
        justify-content: space-between;
        align-items: center;

        image {
          width: 9rpx;
          height: 16rpx;
        }
      }
    }

    .content-foot {
      width: 100%;
      height: 90rpx;
      background: #e0e0e0;
      border-radius: 45rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 32rpx;
      font-weight: 500;
      color: #999999;
      margin-top: 60rpx;
    }
  }
}
</style>
